package com.keyroy.game.puzzle_rpg.views;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;

import com.keyroy.game.puzzle_rpg.views.layouts.CenterLayout;

public class ViewContainer extends ScrolledComposite {

	private Composite view;
	private Composite container;

	public ViewContainer(Composite parent, ViewMaker viewMaker) {
		super(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.DOUBLE_BUFFERED);
		setExpandHorizontal(true);
		setExpandVertical(true);

		container = new Composite(this, SWT.DOUBLE_BUFFERED);
		container.setLayout(new CenterLayout());

		view = viewMaker.getView(container);

		setContent(container);
		setMinSize(container.computeSize(SWT.DEFAULT, SWT.DEFAULT));

		addControlListener(new ControlListener() {

			@Override
			public void controlResized(ControlEvent e) {
				reset(container, view);
			}

			@Override
			public void controlMoved(ControlEvent e) {
				// TODO Auto-generated method stub

			}
		});

		view.addControlListener(new ControlListener() {

			@Override
			public void controlResized(ControlEvent e) {
				reset(container, view);
			}

			@Override
			public void controlMoved(ControlEvent e) {

			}
		});
	}

	public void center(int x, int y) {
		Point point = getSize();
		setOrigin(x - (point.x / 2), y - (point.y / 2));
	}

	public void repaint() {
		redraw();
		view.redraw();
	}

	public void reset() {
		reset(container, view);
	}

	public void reset(Composite container, Composite view) {
		Point size = ViewContainer.this.getSize();
		Point cSize = view.getSize();
		int maxWidth = Math.max(size.x, cSize.x);
		int maxHeight = Math.max(size.y, cSize.y);
		container.setSize(maxWidth, maxHeight);
		setMinSize(container.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		layout();
	}

	public static interface ViewMaker {
		public Composite getView(Composite parent);
	}

}
